// 历史记录模块：支持检索与LLM对话两类记录，含本地持久化与高效序列化
import axios from 'axios'
/**
 * 生成唯一ID（毫秒时间戳 + 随机串）
 * @returns {string}
 */
function generateId() {
  const rand = Math.random().toString(36).slice(2, 10)
  return `${Date.now()}_${rand}`
}

/**
 * 生成记录摘要
 * @param {'retrieve'|'llm'} type
 * @param {any} snapshot
 * @returns {string}
 */
function buildSummary(type, snapshot) {
  if (type === 'retrieve') {
    const kw = snapshot?.form?.keyword || ''
    const total = snapshot?.pagination?.totalResults ?? (Array.isArray(snapshot?.results) ? snapshot.results.length : 0) ?? 0
    return `检索: "${kw}"（${total}条）`
  }
  if (type === 'llm') {
    const prompt = snapshot?.form?.inputText || ''
    const head = prompt.length > 20 ? `${prompt.slice(0, 20)}…` : prompt
    return `LLM: ${head}`
  }
  return '历史记录'
}

export default {
  namespaced: true,
  state() {
    return {
      items: [],
      snapshots: {}
    }
  },
  getters: {
    all: (state) => state.items.slice().sort((a, b) => b.timestamp - a.timestamp),
    byId: (state) => (id) => state.snapshots[id] || null
  },
  mutations: {
    ADD_RECORD(state, { id, type, routeName, timestamp, summary, snapshot }) {
      state.items.unshift({ id, type, routeName, timestamp, summary })
      state.snapshots[id] = snapshot
      // 限制上限，避免无限增长（可调）
      if (state.items.length > 500) {
        const removed = state.items.splice(500)
        removed.forEach(r => { delete state.snapshots[r.id] })
      }
    },
    REPLACE_SNAPSHOT(state, { id, snapshot }) {
      if (state.snapshots[id]) {
        state.snapshots[id] = snapshot
      }
    },
    REMOVE_RECORD(state, id) {
      state.items = state.items.filter(i => i.id !== id)
      delete state.snapshots[id]
    },
    CLEAR(state) {
      state.items = []
      state.snapshots = {}
    },
    SET_ITEMS(state, items) {
      state.items = items
    },
    SET_SNAPSHOTS(state, snapshots) {
      state.snapshots = snapshots
    }
  },
  actions: {
    /**
     * 保存一条历史记录
     * @param context
     * @param {{ type: 'retrieve'|'llm', routeName: string, snapshot: any, id?: string, timestamp?: number, userId?: number }} payload
     * @returns {string} id
     */
    async save({ commit }, payload) {
      const id = payload.id || generateId()
      const timestamp = payload.timestamp || Date.now()
      const summary = buildSummary(payload.type, payload.snapshot)

      try {
        const res = await axios.post('/api/history', {
          history_uid: id,
          type: payload.type,
          route_name: payload.routeName,
          summary: summary,
          snapshot: payload.snapshot,
          user_id: payload.userId // 后端会自行判断 user_id
        })
        if (res.data.status === 'success') {
          commit('ADD_RECORD', {
            id,
            type: payload.type,
            routeName: payload.routeName,
            timestamp,
            summary,
            snapshot: payload.snapshot
          })
          return id
        }
      } catch (e) {
        console.error('保存历史记录失败:', e)
      }
      return null
    },
    /**
     * 读取历史快照
     * @param context
     * @param {string} id
     * @returns {any|null}
     */
    async load({ commit, getters }, id) {
      let snapshot = getters.byId(id)
      if (!snapshot) {
        try {
          const res = await axios.get(`/api/history/${id}`)
          if (res.data.status === 'success' && res.data.data?.snapshot) {
            snapshot = res.data.data.snapshot
            commit('REPLACE_SNAPSHOT', { id, snapshot }) // 缓存到本地
          }
        } catch (e) {
          console.error('加载历史快照失败:', e)
        }
      }
      return snapshot
    },
    /**
     * 从后端获取历史记录列表
     * @param context
     * @param {number} userId
     */
    async fetchHistory({ commit }, userId) {
      try {
        const res = await axios.get('/api/history', { params: { user_id: userId } })
        if (res.data.status === 'success' && Array.isArray(res.data.data?.items)) {
          // 将快照也填充到本地，防止多次请求
          const snapshots = {}
          for (const item of res.data.data.items) {
            if (item.snapshot) {
              snapshots[item.history_uid] = item.snapshot
            }
          }
          commit('SET_ITEMS', res.data.data.items.map(item => ({
            id: item.history_uid,
            type: item.type,
            routeName: item.route_name,
            timestamp: item.timestamp,
            summary: item.summary
          })))
          commit('SET_SNAPSHOTS', snapshots)
        }
      } catch (e) {
        console.error('获取历史记录列表失败:', e)
      }
    },
    /**
     * 删除一条历史记录
     * @param context
     * @param {string} id
     */
    async deleteHistory({ commit }, id) {
      try {
        const res = await axios.delete(`/api/history/${id}`)
        if (res.data.status === 'success') {
          commit('REMOVE_RECORD', id)
        }
      } catch (e) {
        console.error('删除历史记录失败:', e)
      }
    },
    /**
     * 清空所有历史记录 (需要后端支持批量删除或前端循环删除)
     * 目前后端没有批量清空接口，这里暂时先清空本地，后续可考虑实现后端接口。
     * @param context
     */
    async clearAllHistory({ state, dispatch, commit }) {
      // 循环删除每一条，直到后端支持批量删除
      for (const item of state.items) {
        await dispatch('deleteHistory', item.id)
      }
      commit('CLEAR')
    }
  }
}

